import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:light_image/channels/AndroidBackTop.dart';
import 'package:light_image/commom/commom.dart';
import 'package:light_image/pages/root_page.dart';
import 'package:light_image/widget/view/vercode_timer.dart';
import 'package:mobsms/mobsms.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';


class LoginPage extends StatefulWidget {
  LoginPage({
    this.countdown: 10,
  });

  /// 倒计时的秒数，默认60秒。
  final int countdown;

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> implements MyClass1 {
  static const platform = const MethodChannel('app.channel.shared.data');

  @override
  String onSend() {
    getSharedText() async {
      var sharedData = await platform.invokeMethod("getParam");
      if (sharedData != null) {
        var dataShared = sharedData;

        print(dataShared);
      }
    }

    getSharedText();
    Smssdk.getTextCode(_usernameController.text, "86", "16492873",
            (dynamic ret, Map err) {
          if (err != null) {
            toast("发送失败");
          } else {
            toast("已发送");
          }
        });
    return "1111";
  }

  @override
  void initState() {
    read().then((onValue){
      if(onValue!=null&&onValue .isNotEmpty){
          pushAndRemoveUntil(RootPage(), RouterType.material);
      }
    });
    super.initState();
    suffix = getSuffix();
    _usernameController.addListener(() {
      setState(() {
        suffix = getSuffix();
      });
    });
  }

  var _usernameController = TextEditingController();
  var _emailController = TextEditingController();
  StatefulWidget suffix;

  void toast(String msg) {
    Fluttertoast.showToast(
        msg: msg,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  StatefulWidget getSuffix() {
    //如果未输入内容或者手机号格式不对则隐藏发送功能
    if (_usernameController.text.isEmpty) {
      return null;
    }

    return VercodeTimerWidget(this);
  }

  String versionName = "";

  void getVersionName() async {
    final packageInfo = await PackageInfo.fromPlatform();
    versionName = packageInfo.version;
  }

  @override
  Widget build(BuildContext context) {
    getVersionName();


    return Scaffold(
//        resizeToAvoidBottomPadding: true, //输入框抵住键盘
        appBar: AppBar(
          title: Text("登录"),
        ),
        body :body2()
    );

  }

  Widget body2() {

    return WillPopScope(
 onWillPop: () async {
AndroidBackTop.backDeskTop();  //设置为返回不退出app
return false;  //一定要return false
},
child:

    Column(
      children: <Widget>[
        Expanded(
          child:         bodyContent(),
          flex: 1,
        ),
     Container(
              child: Text("北京素玄科技有限公司\n${versionName}",
                  textAlign: TextAlign.center, style: TextStyle()),
              margin: EdgeInsets.fromLTRB(10, 10, 5, 0)),

      ],
    ));
  }

  /**
   * 绝对定位（会出现覆盖现象）
   */
  Widget body1() {
    Stack(
      children: <Widget>[

        Positioned(child: bodyContent()),
        Align(
          alignment: Alignment(0, 0.95),
          child: Container(
              child: Text("北京素玄科技有限公司\n${versionName}",
                  textAlign: TextAlign.center, style: TextStyle()),
              margin: EdgeInsets.fromLTRB(10, 10, 5, 0)),
        )
      ],
    );
  }


  Widget bodyContent() {
//    SizedBox(height: 500.0),
    return SingleChildScrollView(
        child: Padding(
            padding:
            EdgeInsets.only(bottom: 10.0, top: 50, left: 10, right: 10),
            child: Stack(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    Column(children: <Widget>[
                      Image.asset("assets/images/img.png"),
                      Text(
                        "底片云",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 20),
                      ),
                    ]),
                    /*手机号*/
                    TextFormField(
                      inputFormatters: [
//                            WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")),      //限制只允许输入字母和数字
                        WhitelistingTextInputFormatter.digitsOnly,
                        //限制只允许输入数字
                        LengthLimitingTextInputFormatter(11),
                        //限制输入长度不超过8位
                      ],
                      decoration: InputDecoration(
                        suffix: suffix,
                        labelText: "手机号",
                        hintText: "请输入手机号",
//                prefixIcon: Icon(Icons.person)
//                            prefixIcon: ImageIcon(  AssetImage('assets/images/entries_2.png'), color: Colors.blue),
                      ),
                      controller: _usernameController,
                    ),

                    /*验证码*/
                    TextFormField(
                      inputFormatters: [
//                            WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")),      //限制只允许输入字母和数字
                        WhitelistingTextInputFormatter.digitsOnly,
                        //限制只允许输入数字
                        LengthLimitingTextInputFormatter(6),
                        //限制输入长度不超过8位
                      ],
                      decoration: InputDecoration(
                        labelText: "验证码",
                        hintText: "请输入手机验证码",
//                prefixIcon: Icon(Icons.person)
//                            prefixIcon: ImageIcon(
//                                AssetImage('assets/images/entries_2.png'),
//                                size: 25.0,
//                                color: Colors.blue),
                      ),
                      controller: _emailController,
                    ),
                    //登录
                    Container(
                        width: double.infinity,
                        margin: EdgeInsets.fromLTRB(10, 50, 10, 10),
//                          decoration: new BoxDecoration(
//                              gradient: const LinearGradient(
//                                  colors: [Colors.amberAccent, Colors.lightBlue, Colors.red]),
//                              border: Border.all(width: 5.0,color: Colors.green)
//
//                          ),
                        child: gradientButton()
//                          RaisedButton(
//                          child: Text("点击跳转"),
//                          onPressed: () {
//                            _usernameController.text = "点击跳转";
//                          },
//                        )
                    ),
                  ],
                ),
              ],
            )));
  }

  save(String phone) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('phone', phone);
  }

  Future<String> read() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var ph = prefs.getString('phone');
    return ph;
//    if (ph.isNotEmpty) {
//      pushAndRemoveUntil(RootPage(), RouterType.material);
//      return;
//    }
  }

  // 渐变色按钮
  Widget gradientButton() {
    return Container(
      margin: EdgeInsets.fromLTRB(5, 10, 5, 0),
      decoration: BoxDecoration(
          gradient: LinearGradient(colors: [Colors.blueAccent, Colors.blue]),
          // 渐变色
          borderRadius: BorderRadius.circular(5)),
      child: RaisedButton(
//        shape: RoundedRectangleBorder(
////            borderRadius: BorderRadius.circular(25)
//        ),
        color: Colors.transparent,
        // 设为透明色
        elevation: 0,
        // 正常时阴影隐藏
        highlightElevation: 0,
        // 点击时阴影隐藏
        onPressed: () {
          Smssdk.commitCode(
              _usernameController.text, "86", _emailController.text,
                  (dynamic ret, Map err) {
                if (err != null) {
                  toast("验证错误");
                } else {
                  toast("验证Ok");
                  save(_usernameController.text);
                  pushAndRemoveUntil(RootPage(), RouterType.material);
                }
              });
        },
        child: Container(
          alignment: Alignment.center,
//          padding: EdgeInsets.only(bottom: 0,top: 0),
          height: 30,
          child: Text(
            '登 录',
            style: TextStyle(color: Colors.white, fontSize: 15),
          ),
        ),
      ),
    );
  }
}
